//
// Created by wxd on 2025/7/13.
// 渐变三角形：测试引擎的着色器封装
//

#pragma once

#include <iostream>

#include <vector>
#include <glm/glm.hpp>
#include <glm/trigonometric.hpp> // 包含三角函数
#include "../wrapper/log/Logger.h"
#include "../wrapper/monitor/GLDebug.hpp"
#include "../global/ChineseOutput.hpp"
#include "../global/EngineDataProperties.h"
#include "../application/app/Application.h"
#include "../glFramework/shader/Shader.h"

inline const char* vertexPath = "E:\\cpp\\GLRenderEngine\\demo\\shader\\_002\\vertex_shader.glsl";
inline const char* fragmentPath = "E:\\cpp\\GLRenderEngine\\demo\\shader\\_002\\fragment_shader.glsl";

inline std::vector<float> vertices;
inline std::vector<unsigned int> indices;

inline void onResize(int w, int h) {
    glViewport(0, 0, w, h);
    std::cout << "w: " << w << " h: " << h << std::endl;
}

inline void initData() {
    vertices.reserve(9);
    indices.reserve(3);

    // 顶点坐标 + 颜色为一组
    vertices.push_back(0.0f);
    vertices.push_back(0.5f);
    vertices.push_back(0.0f);
    vertices.push_back(1.0f);
    vertices.push_back(0.0f);
    vertices.push_back(0.0f);

    vertices.push_back(0.5f);
    vertices.push_back(-0.5f);
    vertices.push_back(0.0f);
    vertices.push_back(0.0f);
    vertices.push_back(1.0f);
    vertices.push_back(0.0f);

    vertices.push_back(-0.5f);
    vertices.push_back(-0.5f);
    vertices.push_back(0.0f);
    vertices.push_back(0.0f);
    vertices.push_back(0.0f);
    vertices.push_back(1.0f);

    // 索引
    indices.push_back(0);
    indices.push_back(1);
    indices.push_back(2);
}


inline void render() {
    ChineseOutput::init();
    EngineApp.initDefaultWindowConfig();
    EngineApp.setResizeCallback(onResize);
    EngineApp.init();

    initData();

    GLuint VAO;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);

    GLuint VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, fSize(vertices.size()), vertices.data(), GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, fSize(6), reinterpret_cast<void *>(0));
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, fSize(6), reinterpret_cast<void *>(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

    GLuint EBO;
    glGenBuffers(1, &EBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), indices.data(), GL_STATIC_DRAW);

    // 解绑VBO和VAO
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

    const Shader shader(vertexPath, fragmentPath);

    while (EngineApp.update()) {
        GL_CALL(glClear(GL_COLOR_BUFFER_BIT))

        shader.bindProgram();
        GL_CALL(glBindVertexArray(VAO))
        glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, nullptr);
        GL_CALL(glBindVertexArray(0))
        shader.unbindProgram();
    }

    shader.deleteProgram();
    EngineApp.destroy();
}

